package com.example.demo.leetcode.top100;

import java.util.HashMap;
import java.util.Map;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _32复制带随机指针的链表
 * @description
 * @date 2023/06/12 20:44
 * <p>
 * ******************************************************
 */
public class _32复制带随机指针的链表 {
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Map<Node, Node> nodeMap = new HashMap<>();
        Node newHead = new Node(head.val);
        Node q = head;
        Node p = newHead;
        nodeMap.put(q, newHead);
        q = q.next;
        while (q != null) {
            Node newNode = new Node(q.val);
            p.next = newNode;
            nodeMap.put(q, newNode);
            p = p.next;
            q = q.next;
        }

        while (head != null) {
            Node newNode = nodeMap.get(head);
            if (head.random != null) {
                newNode.random = nodeMap.get(head.random);
            }
            head = head.next;
        }
        return newHead;

    }

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
}
